/**
 * This file is part of the educational usermanagement system.
 * 
 * Copyright (c) 2008, Florian Arndt, Thomas Kemptner, Christian Kerl, Patrick Neuberger, Marcel Rehfeld, Emal Sadran, Stefan Sauer
 * 
 * Released under the MIT License http://www.opensource.org/licenses/mit-license.php
 */

package edu.ba.management.data.search.comparer;

import java.util.HashMap;

/**
 * 
 */
public final class EqualityComparerFactory
{
    private static HashMap<Class<?>, IEqualityComparer> cache = new HashMap<Class<?>, IEqualityComparer>();

    /**
     * Gets the IEqualityComparer implementation for a given type.
     * 
     * @param type the type
     * @return the IEqualityComparer implementation
     */
    public static IEqualityComparer getComparer(Class<?> type)
    {
        Class<?> comparer_type;

        try
        {
            comparer_type = ClassLoader.getSystemClassLoader().loadClass(
                    getComparerName(type.getSimpleName()));
            if (!IEqualityComparer.class.isAssignableFrom(comparer_type))
            {
                throw new ClassNotFoundException();
            }
        }
        catch (ClassNotFoundException e)
        {
            comparer_type = DefaultEqualityComparer.class;
        }

        if (!cache.containsKey(comparer_type))
        {
            try
            {
                cache.put(comparer_type, (IEqualityComparer) comparer_type
                        .newInstance());
            }
            catch (Exception e)
            {
            }
        }

        return cache.get(comparer_type);
    }

    /**
     * Gets the fully qualified name of the IEqualityComparer implementation for
     * the given type.
     * 
     * @param basetype the name of the type
     * @return the name of the IEqualityComparer implementation
     */
    private static String getComparerName(String basetype)
    {
        return EqualityComparerFactory.class.getPackage().getName() + "."
                + basetype + "EqualityComparer";
    }
}
